import os
import time
import platform
from playwright.async_api import async_playwright
from ecr_billing_tools import convert_size, create_folder_if_not_exists, print_and_write, upload_localfile_to_s3

async def download(billing_system_url, billing_system_username, billing_system_password, billing_system_month, billing_system_sub_cust_list, upload_mgt_bucket, upload_mgt_prefix_base, s3):
    async with async_playwright() as playwright:
        await run(playwright, billing_system_url, billing_system_username, billing_system_password, billing_system_month, billing_system_sub_cust_list, upload_mgt_bucket, upload_mgt_prefix_base, s3)

async def run(playwright, billing_system_url, billing_system_username, billing_system_password, billing_system_month, billing_system_sub_cust_list, upload_mgt_bucket, upload_mgt_prefix_base, s3):
    browser = await playwright.chromium.launch(args=["--disable-gpu", "--single-process"])
    
    try:
        context = await browser.new_context()
        page = await context.new_page()
        await page.goto(f"{billing_system_url}bill_login.php", timeout=120000)
        await page.get_by_placeholder("Login account").fill(billing_system_username)
        await page.get_by_placeholder("Password").fill(billing_system_password)
        print_and_write(f"使用账号'{billing_system_username}' 登录 {billing_system_url} 中...")
        await page.get_by_role("button", name="Sign In").click()
        print_and_write(f"加载 Dashboard 页面，开始选择月份及账号")

        for sub_cust in billing_system_sub_cust_list:
            for billing_month in billing_system_month:
                try:
                    await page.goto(f"{billing_system_url}bill_cost_dashboard.php")
                    await page.wait_for_load_state('networkidle')
                    print_and_write("-" * 88)
                    print_and_write(f"开始处理 {billing_month}, 账号: {sub_cust}")
                    start = time.time()
                    await page.click("#select2-sel_bill_period-container")
                    await page.get_by_role("textbox").fill(billing_month)
                    await page.get_by_role("textbox").press("Enter")
                    await page.wait_for_load_state('networkidle')
                    await page.click("#select2-sel_sub_cust_id-container")
                    await page.get_by_role("textbox").fill(sub_cust)
                    await page.get_by_role("textbox").press("Enter")
                    await page.wait_for_load_state('networkidle')
                    element = page.locator('li[role="treeitem"].select2-results__option')

                    # 检查元素是否存在
                    if await element.count() > 0:
                        # 获取第一个匹配元素的文本内容
                        text_content = await element.first.inner_text()
                        # 检查文本是否匹配
                        if text_content == "No matching records found":
                            print_and_write(f"账号: {sub_cust} 不存在。")
                            print_and_write("-" * 88)
                            continue

                    await page.wait_for_load_state('networkidle')
                    print_and_write(f"开始下载 {billing_month}, 账号: {sub_cust}")
                    async with page.expect_download(timeout=900000) as download_info:
                        async with context.expect_page(timeout=900000) as page1_info:
                            print_and_write(f"下载页面打开中...")
                            await page.click("#cur_download")
                        page1 = await page1_info.value

                        if page1.url:
                            if await page1.inner_text('body').find('No data for the selected month to generate CUR file') != -1:
                                raise Exception(f"系统返回没有数据下载。")

                    download = await download_info.value
                    print_and_write(f"准备临时文件夹")
                    folder_path = '/tmp'
                    if platform.system() == 'Windows':
                        folder_path = 'C:\\tmp'  # Windows 系统下的路径
                    create_folder_if_not_exists(folder_path)
                    full_path = f"{folder_path}/{download.suggested_filename}"
                    print_and_write(f"下载文件: {download.suggested_filename} 至 {folder_path}")
                    download_path = await download.path()
                    await download.save_as(full_path)
                    file_size = os.path.getsize(full_path)
                    bucket_prefix = f'{upload_mgt_prefix_base}{billing_month.replace("/", "")}/'
                    upload_localfile_to_s3(s3, full_path, upload_mgt_bucket, bucket_prefix, download.suggested_filename)
                    os.remove(full_path)
                    print_and_write(f"删除本地临时文件: {full_path}")
                    end = time.time()
                    print_and_write(f"完成处理，文件大小 {convert_size(file_size)}，总计耗时 {(end - start):.2f} 秒")
                except Exception as e:
                    print_and_write(f"{e}")
                    continue
                finally:
                    if 'page1' in locals():
                        await page1.close()

    except Exception as e:
        print_and_write(f"{e}")
    finally:
        print_and_write("-" * 88)
        await page.close()
        await context.close()
        await browser.close()